<template>
	<view class="content">
		
		<view class="text-area">
			
			<button @tap="send">发送</button>
		</view>
		<view>
			<text class="title">{{title}}</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {

		},
		mounted() {
			this.connectWebSocket('ws://localhost:8080');
		},
		methods: {
			send(){
				this.sendWebSocketMessage('user');
			},
			// 初始化WebSocket连接
			connectWebSocket(url) {
				uni.connectSocket({
					url: url,
					complete: () => {}
				});

				// 打开连接时触发
				uni.onSocketOpen((res) => {
					console.log('WebSocket连接已打开！', res);
				});

				// 接收到服务器消息时触发
				uni.onSocketMessage((res) => {
					// const buffer =res.data.data;
					// const textDecoder =new TextDecoder();
					// let txt =textDecoder.decode(buffer);
					// console.log('text',txt);
					// this.title=this.title+'-'+this.txt;
					var enc = new TextDecoder("utf-8");
					var uint8_msg =new Uint8Array(res.data);
					var msg =enc.decode(uint8_msg);
					this.title=this.title+'/'+msg;
					console.log('========',msg);
					console.log('收到服务器内容：',res.data);
				});

				// 出现错误时触发
				uni.onSocketError((res) => {
					console.error('WebSocket连接打开出错', res);
				});
			},
			// 发送消息
			sendWebSocketMessage(message) {
				uni.sendSocketMessage({
					data: message,
					success: () => {
						console.log('消息发送成功');
					},
					fail: () => {
						console.error('消息发送失败');
					}
				});
			},
			// 关闭WebSocket连接
			closeWebSocket() {
				uni.closeSocket();
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>